package org.imlinker.gui;

import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import org.imlinker.setting.Settings;
import org.imlinker.util.Images;

public class TrayIconPopup extends PopupMenu implements ActionListener {

	public TrayIconPopup(final MainWindow window, final Settings settings) {
		super();

		this.mainWindow = window;
		this.settings = settings;

		// 如果系统支持java托盘图标，则启动托盘图标
		if (SystemTray.isSupported()) {
			initialTrayIcon();
		}

		// Setting
		MenuItem item = new MenuItem("Settings");
		item.addActionListener(this);
		add(item);

		// Status
		Menu menu = new Menu("Status");
		item = new MenuItem("Online");
		item.addActionListener(this);
		menu.add(item);
		item = new MenuItem("Busy");
		item.addActionListener(this);
		menu.add(item);
		item = new MenuItem("Away");
		item.addActionListener(this);
		menu.add(item);
		add(menu);

		item = new MenuItem("Show");
		item.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				window.setVisible(true);
			}

		});
		add(item);

		CheckboxMenuItem openFirstCheck = new CheckboxMenuItem(
				"Open first message");
		openFirstCheck.setState(settings.openFirst());
		openFirstCheck.addItemListener(new ItemListener() {

			public void itemStateChanged(ItemEvent e) {
				settings.setOpenFirst(e.getStateChange() == ItemEvent.SELECTED);
			}

		});
		add(openFirstCheck);

		// Exit.
		item = new MenuItem("Exit");
		item.addActionListener(this);
		add(item);

	}

	private void initialTrayIcon() {

		try {
			Image image = Images.getIcon0();
			trayIcon = new TrayIcon(image, "Linker", this);
			trayIcon.setImageAutoSize(true);
			SystemTray.getSystemTray().add(trayIcon);
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param e
	 *            ActionEvent.
	 */
	public final void actionPerformed(final ActionEvent e) {
		if (e.getActionCommand() == "Exit") {
			settings.save();
			System.exit(0);

		} else if (e.getActionCommand() == "Show") {
			mainWindow.setVisible(true);
		}
	}

	public void setTrayIcon(TrayIcon trayIcon) {
		this.trayIcon = trayIcon;
	}

	public TrayIcon getTrayIcon() {
		return trayIcon;
	}

	public void setMessageNum(int number) {
		if (number == 0) {
			trayIcon.setImage(Images.getIcon0());
		} else if (number == 1) {
			trayIcon.setImage(Images.getIcon1());
		} else if (number == 2) {
			trayIcon.setImage(Images.getIcon2());
		} else if (number == 3) {
			trayIcon.setImage(Images.getIcon3());
		} else {
			trayIcon.setImage(Images.getIcon4());
		}
	}

	private MainWindow mainWindow;

	private Settings settings;

	private TrayIcon trayIcon;

}
